package cn.k7g.alloy.core.objectmapper;

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 全局时间格式化
 * @date  2022/2/25 上午11:00
 * @author victor-wu
 */

public class GlobalDateFormatter extends SimpleDateFormat {

    private String[] patterns = {
            "yyyy-MM-dd",
            "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-dd HH:mm",
            "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
            "EEE, dd MMM yyyy HH:mm:ss zzz",
            "EEE MMM dd HH:mm:ss 'CST' yyyy",
            "yyyy-MM-dd'T'HH:mm:ss.SSS'+'SSSS"
    };

    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
        super.applyPattern("yyyy-MM-dd HH:mm:ss");
        return super.format(date, toAppendTo, fieldPosition);
    }

    @Override
    public Date parse(String s, ParsePosition pos) {
        List<String> formaterList = new ArrayList<>();
        for (String item : patterns) {
            if (item.replaceAll("'", "").length() != s.length()) {
                continue;
            }
            formaterList.add(item);
        }
        for (String format : formaterList) {
            try {
                super.applyPattern(format);
                Date date = super.parse(s, pos);
                if (date == null) {
                    continue;
                }
                return date;
            } catch (Exception ex) {
                continue;
            }
        }
        return null;
    }
}
